package com.bootcamp.ex1125.controller;

import com.bootcamp.ex1125.bean.BaseRespVO;
import com.bootcamp.ex1125.bean.User;
import com.bootcamp.ex1125.exception.InvalidNameException;
import com.bootcamp.ex1125.exception.ParamException;
import com.bootcamp.ex1125.util.ValidatorUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.NoSuchElementException;

/**
 * @program: springboot
 * @description:
 * @author: Keyu Li
 * @create: 2021-11-25 18:50
 **/

@RestController
@RequestMapping("user")
public class UserController {

    @RequestMapping("login")
    public BaseRespVO login(@Valid User user, BindingResult bind, HttpSession session) throws ParamException, InvalidNameException {
        // 本来打算使用 aop代理完成了基本参数校验：name长度，password长度
        // aop无法拦截handler？ 然后打算用 HandlerInterceptor实现，但是怎么获取 bind？
        // 通过工具类实现吧：
        /* 已经解决了这个非常sb的bug：BindingResult 必须写在 valid之后，否则就报错 */
        //ValidatorUtils.valid(bind);
        // 密码不能包含 字母
        if (!user.getPassword().matches("[^a-zA-Z]+"))
            throw new ParamException("密码不能包含字母!");
        // user不能包含 yuanzhi
        if (user.getName().contains("yuanzhi"))
            throw new InvalidNameException("用户名不能是yuanzhi!");
        session.setAttribute("username", user.getName());
        return BaseRespVO.ok("登录成功");
    }

    @RequestMapping("hello")
    public BaseRespVO hello(HttpSession session) {
        Object username = session.getAttribute("username");
        String msg = "恭喜！欢迎！\ncong! welcome " + username;
        return BaseRespVO.ok(msg);
    }
}
